//
//  CalendarView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/2/15.
//

import SwiftUI
import FSCalendar


//需要配合
struct CalendarView<Content: View>: View {
    let yearOrmonth: String
    let events: [String: Any]?
    let viewWidth: Double //试图宽度
    let dayView: (CalendarBean) -> Content

    var body: some View {
        CalendarContainerView(
            yearOrmonth: yearOrmonth,
            events: events,
            dayView: dayView
        )
        .frame(height: getHeight(viewWidth: viewWidth))
    }
    
    private var dateFormatter: DateFormatter {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM"
        return formatter
    }
    
    // 根据日期，计算行数，计算总高度，
    //由于动态更新会导致界面错乱，所以需求提前计算
    private func getHeight(viewWidth: Double) -> CGFloat {
//        let weekdayViewHeight = calendar.calendarWeekdayView.frame.height
        let weekdayViewHeight : CGFloat = 27 + 12  //高度没有完全正确计算，week大概是27，加上一些间距，仅此中文而已
        let itemsWidth = viewWidth / 7
        var height :CGFloat = 0
        if let date = dateFormatter.date(from: yearOrmonth) {
            var calendar = Calendar(identifier: .gregorian)
            calendar.locale = Locale(identifier: "zh_CN") // 与 FSCalendar 的 Locale 一致
            calendar.firstWeekday = 2 // 周一为一周的第一天
            let weeksRange = calendar.range(of: .weekOfMonth, in: .month, for: date)
            let row = weeksRange?.count ?? 0
            height  = (CGFloat(row) * itemsWidth) + weekdayViewHeight
            return height
        }
        return CGFloat(277.5)
    }
}
